#include <string.h>
#include "PopupRsaPublicKeyMsg.hpp"

using namespace Popup;


RsaPublicKeyMsg::RsaPublicKeyMsg(const Message *p_message)
 : AbstractMessage(POPUP_MSG_TYPE_RSA_PUBLIC_KEY),
   receivedKey(0), receivedKeySize(0)
{
  AbstractMessage::deserialize(p_message);
}

RsaPublicKeyMsg::~RsaPublicKeyMsg() {
  if (receivedKey != 0) {
    delete receivedKey;
  }
}

bool RsaPublicKeyMsg::onSend()
{
  const unsigned char *_key;
  size_t _size = sslContext->rsaLocal->getRawPublicKey(&_key);
  return payloadAddData(RsaPublicKeyMsg::RSA_PUBLIC_KEY, _key, _size);
}

bool RsaPublicKeyMsg::onReceive()
{
  if (fields.size() != 1) {
    return false;
  } else {
    const MessageField *_field =
        AbstractMessage::payloadGetField(RSA_PUBLIC_KEY);
    if (_field == 0) {
      return false;
    } else {
      receivedKeySize = _field->size;
      receivedKey = new unsigned char[receivedKeySize];
      memcpy(receivedKey, _field->data, _field->size);
      return true;
    }
  }
}
